/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import com.uaihebert.factory.EasyCriteriaFactory;
import com.uaihebert.model.EasyCriteria;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
 *
 * @author Familia Genu
 */
public class Dao<T> {

    private static EntityManager em =
            Persistence.createEntityManagerFactory("UP").createEntityManager();
    private Class classe;
    protected EasyCriteria<T> criteria;

    public Dao(Class classe) {
        this.classe = classe;
        this.criteria = EasyCriteriaFactory.createQueryCriteria(em, classe);
    }

    public Dao() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void insert(T entidade) {
        em.getTransaction().begin();
        em.persist(entidade);
        em.getTransaction().commit();
    }

    public void update(T entidade) {
        em.getTransaction().begin();
        em.merge(entidade);
        em.getTransaction().commit();
    }

    public void remove(int id) {
        T entidade = get(id);
        if (entidade == null) {
            return;
        }
        em.getTransaction().begin();
        em.remove(entidade);
        em.getTransaction().commit();
    }

    public T get(int id) {
        return (T) em.find(classe, id);
    }

    public List<T> list() {
        return criteria.getResultList();        
    }    

    public void close() {
        em.close();
    }
    
    public Long count() {
        return criteria.count();
    }
    
    public void clearCliteria() {
        criteria = EasyCriteriaFactory.createQueryCriteria(em, classe);
    }
}
